package com.ds.shopping_admin_service.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ds.shopping_admin_service.mapper.AdminMapper;
import com.ds.shopping_common.pojo.Admin;
import com.ds.shopping_common.pojo.Permission;
import com.ds.shopping_common.service.AdminService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;

@DubboService
@Transactional
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    //新增管理员
    @Override
    public int findAdd(Admin admin) {
        int insert = adminMapper.insert(admin);
        return insert;
    }

    //修改管理员
    @Override
    public int update(Admin admin) {
        //如果前端传来的是空密码，则密码还是原来的密码
        if(!StringUtils.hasText(admin.getPassword())){
            //查询原来的密码
            String password = adminMapper.selectById(admin.getAid()).getPassword();
            admin.setPassword(password);
        }

        return adminMapper.updateById(admin);
    }

    //删除管理员
    @Override
    public void delete(Long aid) {
        //删除用户的所有角色
        adminMapper.deleteAdminAllRole(aid);
        //删除用户
        adminMapper.deleteById(aid);
    }

    //通过id查询管理员
    @Override
    public Admin findById(Long aid) {

        return adminMapper.findById(aid);
    }

    //分页查询管理员
    @Override
    public Page<Admin> search(int page, int size) {

        return adminMapper.selectPage(new Page(page,size),null);
    }

    //修改管理员角色
    @Override
    public void updateRoleToAdmin(Long aid, Long[] rids) {
        //删除所有管理员角色
        adminMapper.deleteAdminAllRole(aid);
        //重新添加管理员角色
        for (Long rid : rids) {
            adminMapper.addRoleToAdmin(aid,rid);
        }

    }




    /**
     * 认证授权相关的服务方法
     * @param username
     * @return
     */
    //根据用户名查询用户
    @Override
    public Admin findByAdminName(String username) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        Admin admin = adminMapper.selectOne(queryWrapper);
        return admin;
    }

    //根据用户名查询用户查询用户权限
    @Override
    public List<Permission> findAllPermission(String username) {

        return adminMapper.findAllPermission(username);
    }
}
